#ifndef _FILE_MANAGE_CPP
#define _FILE_MANAGE_CPP

#include "FileManage.h"
#include <list>
#include <string>
using std::list;
using std::string;


// Static members initialization
bool FileManage::instanceFlag_ = false;
FileManage* FileManage::instance_ = NULL;


FileManage::FileManage()
{
	this->meetingFileName_="meeting.dat";
	this->userFileName_="user.dat";
}

FileManage * FileManage::getInstance( void )
{
	if(!instanceFlag_)
	{
		instance_ = new FileManage();
		instanceFlag_ = true;
	}

	return instance_;
}

FileManage::~FileManage()
{
	this->fin_.close();
	this->fout_.clear();
}

std::list<User> FileManage::readUsersFromFile( void )
{
	this->fin_.open(this->userFileName_, std::fstream::in);
	
	list<User> users;
	users.clear();

	string name, password, email, phone;
	User user;
	while(fin_>>name>>password>>email>>phone)
	{
		user.setName(name);
		user.setPassword(password);
		user.setEmail(email);
		user.setPhone(phone);
		users.push_back(user);
	}

	this->fin_.close();

	return users;
}

void FileManage::writeUsersToFile( std::list<User> users )
{
	this->fout_.open(this->userFileName_, std::fstream::out);

	for(list<User>::iterator it = users.begin(); it!=users.end(); ++it)
	{
		fout_ << it->getName() << " " 
			  << it->getPassword() << " "
			  << it->getEmail() << " "
			  << it->getPhone() << "\n";
	}

	fout_.close();
}

std::list<Meeting> FileManage::readMeetingsFromFile( void )
{
	this->fin_.open(this->meetingFileName_, std::fstream::in);

	list<Meeting> meetings;
	meetings.clear();

	string sponsor, participator, startDate, endDate, title;
	Meeting meeting;
	while(fin_>>sponsor>>participator>>startDate>>endDate>>title)
	{
		meeting.setSponsor(sponsor);
		meeting.setParticipator(participator);
		meeting.setStartDate(Date::stringToDate(startDate));
		meeting.setEndDate(Date::stringToDate(endDate));
		meeting.setTitle(title);
		meetings.push_back(meeting);
	}

	this->fin_.close();

	return meetings;
}

void FileManage::writeMeetingsToFile( std::list<Meeting> meetings )
{
	this->fout_.open(this->meetingFileName_, std::fstream::out);

	for(list<Meeting>::iterator it = meetings.begin(); it!=meetings.end(); ++it)
	{
		fout_ << it->getSponsor() << " "
			  << it->getParticipator() << " "
			  << Date::dateToString(it->getStartDate()) << " "
			  << Date::dateToString(it->getEndDate()) << " "
			  << it->getTitle() << "\n";
	}

	fout_.close();
}

#endif // !_FILE_MANAGE_CPP
